import ApiFetchers from "@/apis/api_fetchers"
import { getToken } from "@/utils/cached"
import { genStorageKey } from "@/utils/common"
import { createLogger } from "@/utils/logger"
import { atom, useAtom } from "jotai"
import { atomWithStorage } from "jotai/utils"
import { cloneDeep, isArray } from "lodash"
import { useCallback, useState } from "react"
import { toast } from "react-toastify"
import { generatePlaceholderGames } from "@/features/business/HomePage_deprecated/constant"
import {
    MemberIndexBannerItem,
    RefGameFavListItem,
    RefGamePlatformListItem,
    TypeMemberIndexGameListItem,
    TypeMemberIndexNavListItem,
} from "@/apis/home_page_constant_types"
const logger = createLogger("HOME ATOM")
/**
 * 游戏场商列表
 */

const defaultBannerItem = Object.freeze({
    id: "0",
    type: 0,
    tags: [],
    url: "",
    link: "/",
    back_color: "#fff",
    state: 0,
    is_delete: 0,
    created_at: 0,
    updated_at: 0,
    updated_uid: "0",
    updated_name: " ",
})

const defaultUserWallet = Object.freeze({
    uid: "",
    balance: "0",
    withdrawable: "0",
})

export const gamePlatformListAtom = atom<RefGamePlatformListItem[]>([])
export const favoriteGameAtom = atom<RefGameFavListItem[]>([])
export const favoriteGameMapAtom = atom<Map<string | undefined, RefGameFavListItem>>(new Map())
export const userWalletAtom = atom<ApiTypes.Fetcher.Result.UserWallet>({
    version: 0,
    balance: "0",
    available: "0",
    withdrawable: "0",
    remainingRollover: "0",
})
export const refUserWalletAtom = atom<ApiTypes.Fetcher.Result.RefUserWallet>(defaultUserWallet)

export const homeGamesAtom = atomWithStorage<{
    games: Record<string, TypeMemberIndexGameListItem[]>
    links: Record<string, TypeMemberIndexNavListItem[]>
    banners: MemberIndexBannerItem[]
}>(genStorageKey("member_index"), {
    games: {
        ["Hot Games"]: generatePlaceholderGames(5),
        Slot: generatePlaceholderGames(5),
        Live: generatePlaceholderGames(5),
        Fishing: generatePlaceholderGames(5),
        ["Table Game"]: generatePlaceholderGames(5),
        ["Board Game"]: generatePlaceholderGames(5),
    },
    links: {},
    banners: [cloneDeep(defaultBannerItem)],
})

/**
 * @init 用于是首请求数据
 * @description 获取收藏游戏列表
 */
export const useFavoriteGame = () => {
    const [isLoading, setIsLoading] = useState<boolean>(false)
    const [favoriteList, setFavoriteList] = useAtom<RefGameFavListItem[]>(favoriteGameAtom)
    const [favMap, setFavMap] =
        useAtom<Map<string | undefined, RefGameFavListItem>>(favoriteGameMapAtom)
    const getFavoriteGameList = useCallback(async () => {
        setIsLoading(true)
        const res = await ApiFetchers.refGetGameFav({
            page: 1,
            page_size: 1000,
        }).finally(() => {
            setIsLoading(false)
        })
        if (res) {
            setFavoriteList(res.d ?? [])
            setFavMap(new Map((res?.d || []).map((it: RefGameFavListItem) => [it.id, it])))
        }
        logger.debug("getFavoriteGameList", res)
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    const handleFavorite = useCallback(
        async (id: string) => {
            if (isLoading) return
            setIsLoading(true)
            const favIndex = favoriteList.findIndex((item) => item.id === id)
            if (favIndex > -1) {
                const res = await ApiFetchers.refGetDeleteGameFav({
                    id,
                }).catch(({ message }) => {
                    if (message) {
                        toast.error(message)
                    }
                    setIsLoading(false)
                })
                logger.debug("removeFavoriteGame", res)
            } else {
                const res = await ApiFetchers.refInsertGameFav({ id }).catch(({ message }) => {
                    if (message) {
                        toast.error(message)
                    }
                    setIsLoading(false)
                })
                logger.debug("addFavoriteGame", res)
            }
            await getFavoriteGameList()
            setIsLoading(false)
        },
        [isLoading, favoriteList, getFavoriteGameList],
    )

    const clearFavorite = useCallback(() => {
        setFavoriteList([])
        setFavMap(new Map())
    }, [setFavoriteList, setFavMap])

    return {
        getFavoriteGameList,
        handleFavorite,
        clearFavorite,
        favoriteList,
        favMap,
        isLoading,
    }
}

/**
 *
 * @description 获取用户余额
 */
export const useUserWallet = () => {
    const [wallet, setWallet] = useAtom<ApiTypes.Fetcher.Result.RefUserWallet>(refUserWalletAtom)

    const getUserWallet = useCallback(async () => {
        const token = getToken()
        if (!token?.accessToken) {
            return
        }
        try {
            const res = await ApiFetchers.refGetFinanceWallet()

            if (res) {
                setWallet(res)
            }
        } catch (err) {
            logger.debug("useUserWallet", err)
        }
    }, [setWallet])

    const clearUserWallet = useCallback(() => {
        setWallet(cloneDeep(defaultUserWallet))
    }, [setWallet])

    return {
        wallet,
        getUserWallet,
        clearUserWallet,
    }
}

/**
 *
 * @description 游戏场商
 */
export const useGamePlatformListAtom = () => {
    const [platformList, setPlatformList] = useAtom<RefGamePlatformListItem[]>(gamePlatformListAtom)
    const getPlatformList = useCallback(async () => {
        try {
            const res = await ApiFetchers.refPlatformList({
                page: 1,
                page_size: 100,
                game_type: "0",
            })
            if (res && Array.isArray(res.d)) {
                setPlatformList(res.d)
            }
        } catch (err) {
            logger.debug("useUserWallet", err)
        }
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [])

    return {
        platformList,
        getPlatformList,
    }
}

export const loadHomeGameAtom = atom(null, async (_get, set) => {
    const res = await ApiFetchers.refGetIndexCache()
    //@ts-ignore
    const { list = {}, nav = {}, banners = [] } = res || {}
    set(homeGamesAtom, {
        games: list || {},
        links: nav || {},
        banners: isArray(banners) && banners.length ? banners : [cloneDeep(defaultBannerItem)],
    })
})
